#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
创建系统管理员用户
"""

import sys
import os
from werkzeug.security import generate_password_hash

# 添加项目根目录到Python路径
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, project_root)

try:
    from app import create_app
    from backend.infrastructure.database import db
    from backend.models.user import User
    from backend.models.role import Role
    from backend.models.permission import Permission
    from backend.models.user_role import UserRole
except ImportError as e:
    print(f"❌ 导入模块失败: {e}")
    print(f"当前工作目录: {os.getcwd()}")
    print(f"Python路径包含: {sys.path}")
    sys.exit(1)

def create_system_admin():
    """创建系统管理员用户"""
    
    # 检查是否已存在系统管理员用户
    admin_user = User.query.filter_by(username='系统管理员').first()
    if admin_user:
        print("⚠️ 系统管理员用户已存在")
        print(f"   用户名: {admin_user.username}")
        print(f"   真实姓名: {admin_user.real_name}")
        print(f"   手机号: {admin_user.mobile}")
        
        # 检查权限数量
        try:
            user_permissions = []
            for role in admin_user.roles:
                print(f"   检查角色: {role.name} (ID={role.id})")
                role_permissions = list(role.permissions)
                print(f"     该角色权限数: {len(role_permissions)}")
                for permission in role_permissions:
                    user_permissions.append(permission.code)
            user_permissions = list(set(user_permissions))  # 去重
            print(f"   当前权限数量: {len(user_permissions)}")
        except Exception as e:
            print(f"   ❌ 权限统计失败: {e}")
            print(f"   角色数量: {len(admin_user.roles)}")
            user_permissions = []
        
        return admin_user
    
    # 创建管理员用户
    admin_user = User(
        username='系统管理员',
        real_name='系统管理员',
        mobile='13800000001',
        password_hash=generate_password_hash('111111'),
        status='active'
    )
    
    db.session.add(admin_user)
    db.session.flush()  # 获取用户ID
    
    # 分配admin角色
    admin_role = Role.query.filter_by(name='admin').first()
    if admin_role:
        admin_user.roles.append(admin_role)
        print(f"✅ 为用户分配了 {admin_role.name} 角色")
    else:
        print("⚠️ 未找到admin角色，请先运行权限初始化脚本")
    
    db.session.commit()
    
    # 统计最终权限数量
    try:
        user_permissions = []
        for role in admin_user.roles:
            print(f"   为用户分配的角色: {role.name}")
            role_permissions = list(role.permissions)
            print(f"     该角色权限数: {len(role_permissions)}")
            for permission in role_permissions:
                user_permissions.append(permission.code)
        user_permissions = list(set(user_permissions))  # 去重
    except Exception as e:
        print(f"   ❌ 权限统计失败: {e}")
        user_permissions = []
    
    print("✅ 系统管理员创建成功！")
    print(f"   用户名: {admin_user.username}")
    print(f"   密码: 111111")
    print(f"   真实姓名: {admin_user.real_name}")
    print(f"   手机号: {admin_user.mobile}")
    print(f"   拥有权限数量: {len(user_permissions)}")
    
    # 检查是否有90个权限
    total_permissions = Permission.query.filter_by(status='active').count()
    print(f"   系统总权限数: {total_permissions}")
    
    if len(user_permissions) != total_permissions:
        print(f"   ⚠️ 警告：admin角色权限数({len(user_permissions)})与系统总权限数({total_permissions})不一致！")
        print("   建议运行权限补全脚本")
    
    return admin_user

if __name__ == '__main__':
    app = create_app()
    with app.app_context():
        try:
            create_system_admin()
        except Exception as e:
            print(f"❌ 创建管理员失败: {e}")
            db.session.rollback()
            raise
